package com.lanou.musicproject.adapter;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.musicproject.R;
import com.lanou.musicproject.activity.DownloadActivity;
import com.lanou.musicproject.activity.MainActivity;
import com.lanou.musicproject.activity.MusicPlayActivity;
import com.lanou.musicproject.activity.RankMatter;
import com.lanou.musicproject.bean.MyMusicList;
import com.lanou.musicproject.bean.Rank;
import com.lanou.musicproject.bean.RankContent;
import com.lanou.musicproject.bean.RankShowLink;
import com.lanou.musicproject.event.MyEvent;
import com.lanou.musicproject.suspendservice.FxService;
import com.lanou.musicproject.utils.MusicPlayer;
import com.lanou.musicproject.utils.MyConfig;
import com.lanou.musicproject.volley.VolleySingleton;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by dllo on 15/10/20.
 */
public class RankMatterListViewAdapter extends BaseAdapter {

    private boolean isService = false;

    private ArrayList<RankContent.SongListEntity> data;


    private List<RankShowLink.SongurlEntity.UrlEntity> data_url;

    private Context mContext;
    private RankContent.SongListEntity entity;
    private VolleySingleton volleySingleton;
    private MusicPlayer musicPlayer;
    private String show_link;
    public boolean isStart = true;
    public boolean isPlaying = false;
    private ViewHolder holder;


    public RankMatterListViewAdapter(Context c, ArrayList<RankContent.SongListEntity> r) {
        mContext = c;
        data = r;

        musicPlayer = new MusicPlayer();
    }

    @Override
    public int getCount() {
        return data != null && data.size() > 0 ? data.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return data != null && data.size() > 0 ? data.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.rankcontent_item, null);
            holder = new ViewHolder();
            holder.rankcontent_Pic = (ImageView) convertView.findViewById(R.id.rankcontent_Pic);
            holder.rankcontent_title = (TextView) convertView.findViewById(R.id.rankcontent_title);
            holder.rankcontent_author = (TextView) convertView.findViewById(R.id.rankcontent_author);
            holder.rank_menu = (ImageView) convertView.findViewById(R.id.rank_menu);
            holder.playBtn = (Button) convertView.findViewById(R.id.play_online);
            holder.itmeView = (LinearLayout) convertView.findViewById(R.id.itemView);

            volleySingleton = VolleySingleton.getInstance(mContext);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        entity = (RankContent.SongListEntity) getItem(position);
        holder.rankcontent_author.setText(entity.getAuthor());
        holder.rankcontent_title.setText(entity.getTitle());
        /**
         * 歌词地址url
         * entity.getLrclink()
         */


        /**
         *
         * 点击行布局播放
         *
         * */

        holder.itmeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<MyMusicList> lists = new ArrayList<>();
                for (RankContent.SongListEntity entity : data) {
                    MyMusicList musicList = new MyMusicList();
                    musicList.setName(entity.getTitle());
                    musicList.setSinger(entity.getAuthor());
                    musicList.setSongId(entity.getSong_id());
                    musicList.setPlayer_singer_image(entity.getPic_big());

                    /**
                     * 歌词下载
                     */



                    String s = entity.getSong_id();
                    Log.i("---->>", s);
                    musicList.setFrom("网络");
                    lists.add(musicList);
                }
                MainActivity.mini_play(lists, position);
                FxService.mini_play(lists, position);
                MusicPlayActivity.playIv(lists, position);


            }
        });


        String url = entity.getPic_small();

        Picasso.with(mContext).load(url).into(holder.rankcontent_Pic);

        holder.playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /**
                 *
                 * 点击后将状态传到播放器
                 *
                 * */
                isPlaying = true;
                MyConfig.putSharePre(mContext, "isPlaying", "isPlaying", isPlaying);


                String url_id = data.get(position).getSong_id();

                String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                        url_id + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                        "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";

                //解析下载地址
                JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        String str = response.toString();
                        RankShowLink link = JSON.parseObject(str, RankShowLink.class);
                        data_url = link.getSongurl().getUrl();
                        show_link = data_url.get(0).getShow_link();

                        //判断播放状态

                        //第一个判断 正在播放 && 按钮是开始,点击暂停,按钮切换成暂停
                        if (musicPlayer.isPlaying() && (isStart = true)) {
                            //如果播放器正在运行
                            musicPlayer.stop();
                            isStart = false;
                            //holder.playBtn.setBackgroundResource(R.mipmap.pause32);
                        }
                        //第二个判断 按钮是开始&&播放器空闲
                        else if ((!musicPlayer.isPlaying()) && (isStart = true)) {
                            musicPlayer.playUrl(show_link);
                            isStart = false;
                            //holder.playBtn.setBackgroundResource(R.mipmap.pause32);
                        }
                        //按钮是暂停状态 播放器空闲 再点击继续播放
                        else {

                            musicPlayer.start();
                            isStart = true;
                            //holder.playBtn.setBackgroundResource(R.mipmap.play_32px);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                volleySingleton.addQueue(jr);
            }

        });


        holder.rank_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                {
                    switch (v.getId()) {
                        case R.id.rank_menu:
                            PopupMenu pm = new PopupMenu(mContext, v);
                            pm.inflate(R.menu.menu_popup);
                            pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    switch (item.getItemId()) {
                                        case R.id.rank_share://分享
                                            share();//集成分享化组件
                                            break;
                                        case R.id.rank_collect://收藏
                                            break;
                                        case R.id.rank_download://下载
                                            Intent intent = new Intent(mContext, DownloadActivity.class);
                                            String song_id = data.get(position).getSong_id();

                                            String filename = data.get(position).getTitle();
                                            MyConfig.putSharePre(mContext, "filename", "filename", filename);

                                            //intent.putExtra("song_id", song_id);
                                            intent.putExtra("entity", data.get(position));
                                            mContext.startActivity(intent);

                                            break;
                                    }
                                    return false;
                                }

                            });
                            pm.show();
                            break;
                    }
                }

            }
        });


        return convertView;
    }

    private void share() {

    }

    private class ViewHolder {
        private ImageView rankcontent_Pic, rank_menu;
        private TextView rankcontent_title, rankcontent_author;
        private Button playBtn;


        public LinearLayout itmeView;
    }

    public boolean IsService(Context mContext, String serviceName) {
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals("com.lanou.musicproject.suspendservice.FxService")) {
                isService = true;
                break;
            }
        }
        return isService;

    }

}
